#include "GunState.h"

/*
Check current targetRect to check what state gun is, by distance of gun and target:
State: Up, Down, Left, Right, HalfUp, HalfDown
*/
void GunState::_updateGunState() {
	int gunDirection;

	double targetX = _armyData->targetRect->X;
	double targetY = _armyData->targetRect->Y;

	double gunX = _armyData->getRect()->X;
	double gunY = _armyData->getRect()->Y;

	double k  = (targetY - gunY) / abs(gunX - targetX);
	double absK = abs(k);

	gunDirection = _GUN_DIRECTION_NONE;


	if (absK < 1.5) {
		// Check left or right 
		if (targetX < gunX - _BULLET_DISTANCE_DELTA) {
			gunDirection = _GUN_DIRECTION_LEFT;
		}
		else if (targetX > gunX + _BULLET_DISTANCE_DELTA) {
			gunDirection = _GUN_DIRECTION_RIGHT;
		}
		if (absK > 0.5) {
			int temp = (k / 0.25);
			temp = temp % 2 == 0? temp : temp + 1;
			gunDirection += temp > 0 ? temp / 2 :  - temp / 2 + 3;
		}
	} else {
		gunDirection = k > 0 ? _GUN_DIRECTION_UP : _GUN_DIRECTION_DOWN;
	}

	_armyData->sprites->currentSprite->setIndex(gunDirection);

}

GunState::GunState(ArmyData* data) {
	_armyData = data;
	_counter = 0;
}

void GunState::initSprites() {
	_armyData->initSpriteHandler();
	_armyData->sprites->addSprite(1, _ID_ARMY_GUN_1, 0);
	_armyData->sprites->addSprite(2, _ID_ARMY_GUN_1_EFFECT, 0);
	_armyData->sprites->addSprite(3, _ID_ARMY_GUN_1_BEFORE, 20);
	_armyData->sprites->setState(1);
}

void GunState::update(long timetick) {
	_armyData->sprites->updateCurrent();
	if (_armyData->_checkInRange()) {
		_updateGunState();
	} else {
		_armyData->sprites->setState(3);
	}

}

void GunState::draw(long timetick) {
	_counter++;
	if (_counter % 20 == 0 && _armyData->_checkInRange()) {
		_currentStateIndex = _armyData->sprites->currentSprite->currentIndex();
		_armyData->sprites->setState((_armyData->sprites->state + 2) % 2 + 1);
		_armyData->sprites->currentSprite->setIndex(_currentStateIndex);
		_counter = 1;
	}
	_armyData->bulletContainer->draw(timetick);
	_armyData->sprites->draw();
}